package srv

import (
	"context"
	"errors"
	"vehicle_management_srv/config"
	"vehicle_management_srv/internal/dao"
	pb "vehicle_management_srv/proto"
)

type Servers struct {
	pb.UnimplementedVehicleServer
}

func (s *Servers) VehicleCreate(c context.Context, req *pb.VehicleCreateReq) (*pb.VehicleCreateResp, error) {
	vehicle := dao.VehicleDetails{
		VehicleName:   req.VehicleName,
		VehicleNumber: req.VehicleNumber,
		Certified:     int8(req.Certified),
	}
	id, message := vehicle.VehicleCreate(req.DriverId)
	if message != "" {
		return &pb.VehicleCreateResp{Id: 0}, errors.New(message)
	}
	return &pb.VehicleCreateResp{Id: int64(id)}, nil
}

func (s *Servers) VehicleUpdate(c context.Context, req *pb.VehicleUpdateReq) (*pb.VehicleUpdateResp, error) {
	var v dao.VehicleDetails
	message := v.VehicleUpdate(req.VehicleId, req.Certified)
	if message != "" {
		return &pb.VehicleUpdateResp{}, errors.New(message)
	}
	return &pb.VehicleUpdateResp{}, nil
}

func (s *Servers) VehicleShow(c context.Context, req *pb.VehicleShowReq) (*pb.VehicleShowResp, error) {
	var v dao.VehicleDetails
	show, message := v.VehicleShow(req.VehicleId)
	if message != "" {
		return &pb.VehicleShowResp{Certified: show}, errors.New(message)
	}
	return &pb.VehicleShowResp{Certified: show}, nil
}

func (s *Servers) VehicleSearch(c context.Context, req *pb.VehicleSearchReq) (*pb.VehicleSearchResp, error) {
	var v dao.VehicleDetails
	search, message := v.VehicleSearch(req.Name)
	if message != "" {
		return &pb.VehicleSearchResp{
			VehicleName:   "",
			VehicleNumber: "",
			Certified:     0,
		}, errors.New(message)
	}
	return &pb.VehicleSearchResp{
		VehicleName:   search.VehicleName,
		VehicleNumber: search.VehicleNumber,
		Certified:     int64(search.Certified),
	}, nil
}

func (s *Servers) VehicleRank(c context.Context, req *pb.VehicleRankReq) (*pb.VehicleRankResp, error) {
	key := "vehicle"
	revRange := config.RDB.ZRevRange(key, 0, 10).Val()
	var list []*pb.Rank
	for _, v := range revRange {
		l := pb.Rank{
			VehicleName: v,
		}
		list = append(list, &l)
	}
	return &pb.VehicleRankResp{List: list}, nil
}
